package com.fly.docker.web;

import java.net.URI;
import java.util.Collections;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.fly.core.entity.JsonResult;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.spotify.docker.client.DefaultDockerClient;
import com.spotify.docker.client.DockerClient;
import com.spotify.docker.client.exceptions.DockerException;
import com.spotify.docker.client.messages.Container;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/ribbon/")
@Api(tags = "ribbon接口")
public class RibbonWebApi
{
    DockerClient dockerClient;
    
    String dockerRemoteAddress;
    
    @Autowired
    RestTemplate restTemplate;
    
    @Autowired
    LoadBalancerClient loadBalancerClient;
    
    @ApiOperation("打印节点")
    @GetMapping("/instance")
    public ServiceInstance logInstance()
    {
        ServiceInstance instance = loadBalancerClient.choose("microservice-docker");
        log.info("INSTANCE URI: {}", instance.getUri());
        return instance;
    }
    
    @ApiOperation("ping")
    @GetMapping("/ping")
    public String ping()
    {
        return restTemplate.getForObject("http://microservice-docker//_ping", String.class);
    }
    
    @ApiOperation("运行容器列表")
    @ApiOperationSupport(order = 30)
    @GetMapping("/listContainers")
    public JsonResult<?> listContainers()
        throws DockerException, InterruptedException
    {
        // 获取负载均衡节点
        ServiceInstance instance = loadBalancerClient.choose("microservice-docker");
        log.info("INSTANCE URI: {}", instance.getUri());
        
        // 初始化
        dockerClient = DefaultDockerClient.builder().uri(URI.create(instance.getUri().toString())).build();
        if (StringUtils.equals("OK", dockerClient.ping()))
        {
            dockerRemoteAddress = instance.getUri().toString();
        }
        
        // 判断状态
        if (StringUtils.isBlank(dockerRemoteAddress))
        {
            throw new DockerException("请先正确初始化DockerClient");
        }
        List<Container> containers = dockerClient.listContainers();
        return JsonResult.success(Collections.singletonMap("containers", containers));
    }
}
